package com.strato.rule.core.v1_0_0.execution;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import com.strato.base.osgi.v1_0_0.BundleUtil;
import com.strato.json.v1_0_0.exec.JSONUtils;
import com.strato.rule.core.v1_0_0.activator.Activator;
import com.strato.serializer.api.v1_0_0.ObjectSerializer;

public class RuleSet {

	private String id;
	
	private String name;
	
	private String description;
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	private List<RuleItem> ruleItems=new ArrayList<RuleItem>();
	
	public void addRuleItem(RuleItem ruleItem){
		ruleItems.add(ruleItem);
	}

	public List<RuleItem> getRuleItems() {
		return ruleItems;
	}

	public void setRuleItems(List<RuleItem> ruleItems) {
		this.ruleItems = ruleItems;
	}

	public void execte(Session session) throws RuleExecutionException{
		if(ruleItems!=null){
			for(RuleItem ri:ruleItems){
				ri.execute(session);
			}
		}
	}
	
	public String toString(){
		ObjectSerializer serializer = BundleUtil.getCachedService(Activator.getContext(), ObjectSerializer.class, null);
		StringWriter sw=new StringWriter();
		try {
			serializer.serialize(this, sw);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return sw.toString();
	}
	
	public static RuleSet fromString(String s){
		StringReader sr=new StringReader(s);
		ObjectSerializer serializer = BundleUtil.getCachedService(Activator.getContext(), ObjectSerializer.class, null);
		try {
			return (RuleSet) serializer.deserialize(sr);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public String toJson(){
		String result = "";
		try {
			result =  JSONUtils.getInstance().toJSON(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
